<template>
    <div class="shrink-0 w-100px h-40px">
        <img class="wh-full" :src="imageUrl" alt="" @click="loadImg()" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import axios from 'axios'
import { getServerUrl } from '~/.env-config'

const props = defineProps<{
    value: string | number | boolean | undefined
}>()

const emit = defineEmits(['update:value'])

watch(
    () => props.value,
    (newV) => {
        if (newV === '') {
            loadImg()
        }
    }
)

defineOptions({ name: 'ImageVerify' })

const serverUrl = getServerUrl(import.meta.env)

const imageUrl = ref('')

function loadImg() {
    axios
        .get(`${serverUrl}/api/captcha`, {
            responseType: 'arraybuffer'
        })
        .then((response) => {
            // 获取图片的二进制数据
            const imageData = response.data
            // 将ArrayBuffer转换为Blob对象
            const blob = new Blob([imageData], { type: 'image/jpeg' })

            // 创建URL对象并将其赋值给<img>的src属性
            imageUrl.value = URL.createObjectURL(blob)
            emit('update:value', response.headers['jbcapkey'])
        })
        .catch((error) => {
            // 处理错误
            console.error(error)
        })
}

onMounted(() => {
    loadImg()
})
</script>

<style scoped></style>
